<template>
  
    <van-list
        v-model:error="error"
        error-text="请求失败，点击重新加载"
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
    >
      <slot name="list" :list="list"></slot>
    </van-list>
  
  <div style="height: 50px"></div>
</template>

<script>
import {ref} from "vue";
import {useRoute} from "vue-router";
import PageConst from "@/consts/pageConst";

export default {
  name: "LoadList",
  props: {
    loadFunc: {
      type: Function,
      required: true
    },
    params: {
      type: Array
    },
    size: {
      type: Number,
      default: PageConst.DEFAULT_PAGE_SIZE
    },
  },
  data(){
    return {
      list: [],
      loading: false,
      finished: false,
      refreshing: false,
      error: false,
      page: -1
    }
  },
  methods: {
    remove(index, ...items){
      this.list.splice(index, 1, ...items)
    },
    unshift(o){
      this.list.unshift(o)
    },
    async onLoad(){
      if(this.loadFunc === null){
        this.error = true
      }else if(typeof this.loadFunc !== 'function'){
        this.error = true
      }

      if (this.refreshing) {
        this.list = [];
        this.refreshing = false;
      }
      
      try {
        // let lastId = this.list.length > 0?this.list[this.list.length - 1][this.idKey]:null
        let {list, page} = await this.loadFunc(...this.params, {page: this.page + 1, size: this.size})
        this.list.push(...list)
        this.page += 1
        if(list.length < this.size){
          this.finished = true
        }
      }catch (e){
        this.error = true
      }finally {
        this.loading = false
      }
    },
    refresh(){
      // 清空列表数据
      this.page = -1
      this.finished = false;
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.onLoad();
    }
  }
}
</script>

<style scoped>

</style>